from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Message
from .forms import MessageForm
from django.contrib.auth.decorators import login_required


def home(request):
    # 获取最新的资讯（按发布时间降序）
    latest_news = ["采访1", "采访2", "采访3"]
    # latest_news = News.objects.all().order_by('-date_posted')[:5]  # 获取最新5条新闻
    # return render(request, 'home.html', {'latest_news': latest_news})
    return render(request, 'main/home.html', {'latest_news': latest_news})

def about(request):
    return render(request, 'main/about.html')

# def works(request):
#     return render(request, 'main/works.html')

# def board(request):
#     return render(request, 'main/board.html')

def works(request):
    # 定义作品的列表
    works_list = {
        "校内作品": [
            {"title": "《闯入森林》", "role": "讲述者"},
            {"title": "《红男绿女》", "role": "巴尼根警官"},
            {"title": "《前哨》", "role": "胡也频"},
            {"title": "《致埃文汉森》", "role": "杰瑞德可兰曼；拉里·墨菲"},
        ],
        "商演作品": [
            {"title": "《new box》", "role": "摇滚90度"},
            {"title": "《灯塔》", "role": "怀恩"},
            {"title": "《人间失格》", "role": "多功能人"},
            {"title": "《辛吉路的画材店》", "role": "塞修"},
            {"title": "《唐人街探案1》", "role": "越南仔"},
            {"title": "《星图》", "role": "江清源"},
        ]
    }
    return render(request, 'main/works.html', {'works_list': works_list})



def board(request):
    # 获取所有未删除的留言，按时间倒序排序
    messages = Message.objects.filter(is_deleted=False).order_by('-created_at')

    # 处理留言表单提交
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            # 保存新的留言
            form.save()
            return redirect('main:board')  # 提交后重定向到留言板页面
    else:
        form = MessageForm()  # GET请求时返回空表单

    # 渲染留言板页面，包含留言列表和表单
    return render(request, 'main/board.html', {'messages': messages, 'form': form})


@login_required  # 确保只有登录的管理员可以删除
def delete_message(request, message_id):
    try:
        message = Message.objects.get(id=message_id)
        
        # 如果不是管理员，返回无权限错误
        if not request.user.is_staff:
            return HttpResponse("无权限删除留言", status=403)
        
        message.is_deleted = True  # 设置为已删除
        message.save()
        
        # 删除后跳转到留言板页面
        return redirect('main:board')  # 修改为正确的路由名称

    except Message.DoesNotExist:
        return HttpResponse("留言不存在", status=404)
